package com.edu.whty.task.init;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edu.whty.common.constants.Constant;
import com.edu.whty.common.tools.DateUtils;
import com.edu.whty.common.tools.HttpClient;
import com.edu.whty.common.tools.OpenUtil;
import com.edu.whty.common.tools.StringUtil;
import com.edu.whty.common.tools.redis.RedisUtil;
import com.edu.whty.entity.base.AttachFile;
import com.edu.whty.entity.base.JobMonitor;
import com.edu.whty.entity.base.Pagination;
import com.edu.whty.entity.base.SpecialRepo;
import com.edu.whty.entity.disk.DiskOwner;
import com.edu.whty.entity.school.ProdOwner;
import com.edu.whty.entity.school.SpecialResourceCatalog;
import com.edu.whty.entity.school.SpecialResourcesBase;
import com.edu.whty.entity.school.VisualRangePrivDto;
import com.edu.whty.service.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Transactional
public class ResourceOrgJob {
	@Resource
	private JdbcTemplate jdbcTemplate;



	private Logger logger = LoggerFactory.getLogger(getClass());


	@Autowired
	private  RedisUtil redisUtil;

	@Autowired
	private JobMonitorService jobMonitorService;

	@Autowired
	private DiskService diskService;
	@Autowired
	private SchoolResourceService schoolResourceService;

	@Autowired
	private SpecialRepoService specialRepoService;

	@Autowired
	private AttachFileService attachFileService;

	@Value("${rrtbk.isCloud}")
	private boolean isCloud;

	@Value("${rrtbk.opengateDomain}")
	private String opengateDomain;


	@Value("${rrtbk.orgId}")
	private String orgId;
	
	@Scheduled(cron="1 * * * * ?")
	public void initDiskOwner() {
		if(!isCloud&&!redisUtil.hasKey(Constant.INIT_DISK_JOB)) {
			JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.INIT_DISK_JOB);
			if(null == jobMonitor) {
				try {
					List<String> userArr = OpenUtil.getSchoolUserIds();
					if(userArr !=null && userArr.size()!=0){
						JobMonitor monitor0 = new JobMonitor();
						monitor0.setJobId(Constant.INIT_DISK_JOB);
						monitor0.setStatus("0");
						monitor0.setSynCount(0);
						monitor0.setUserAmount(userArr.size());
						monitor0.setUserIds("");
						jobMonitorService.addJobMonitor(monitor0);
						redisUtil.set(Constant.INIT_DISK_JOB,"1",7200);
					}
				} catch (Exception e) {
					logger.error("获取教师列表异常",e);
				}
			}else {
				redisUtil.set(Constant.INIT_DISK_JOB,"1",7200);
			}
		}
		if(!isCloud&&!redisUtil.hasKey(Constant.SYN_DISK_JOB)) {
			JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.SYN_DISK_JOB);
			if(null == jobMonitor) {
				JobMonitor jobMonitorInit = jobMonitorService.getJobMonitor(Constant.INIT_DISK_JOB);
				if(null != jobMonitorInit && "1".equals(jobMonitorInit.getStatus())) {
					JobMonitor monitor0 = new JobMonitor();
					monitor0.setJobId(Constant.SYN_DISK_JOB);
					monitor0.setStatus("0");
					monitor0.setSynTime(jobMonitorInit.getSynTime());
					jobMonitorService.addJobMonitor(monitor0);
					redisUtil.set(Constant.SYN_DISK_JOB, "1",7200);
				}
			}else {
				redisUtil.set(Constant.SYN_DISK_JOB,"1",7200);
			}
		}
		if(!isCloud&&!redisUtil.hasKey(Constant.SYN_DISK_PLAT_JOB)) {
			JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.SYN_DISK_PLAT_JOB);
			if(null == jobMonitor) {
				JobMonitor jobMonitorInit = jobMonitorService.getJobMonitor(Constant.INIT_DISK_JOB);
				if(null != jobMonitorInit && "1".equals(jobMonitorInit.getStatus())) {
					JobMonitor monitor0 = new JobMonitor();
					monitor0.setJobId(Constant.SYN_DISK_PLAT_JOB);
					monitor0.setStatus("0");
					monitor0.setSynTime(jobMonitorInit.getSynTime());
					jobMonitorService.addJobMonitor(monitor0);
					redisUtil.set(Constant.SYN_DISK_PLAT_JOB, "1",7200);
				}
			}else {
				redisUtil.set(Constant.SYN_DISK_PLAT_JOB,"1",7200);
			}
		}
	}
	@Scheduled(cron = "0 */5 * * * ?")
	public void synUserDisks(){
			try {
				if(redisUtil.hasKey(Constant.INIT_DISK_STATUS)){
					logger.info("已有执行初始化,不进行初始化");
				}else {
					JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.INIT_DISK_JOB);
					if(null == jobMonitor) {
						logger.info("不进行初始化");
					}else if("0".equals(jobMonitor.getStatus())){
						List<String> userArr = OpenUtil.getSchoolUserIds();
						redisUtil.set(Constant.INIT_DISK_STATUS,"1",7200);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String dateStr= sdf.format(new Date());
						for(int i = jobMonitor.getSynCount();i<jobMonitor.getUserAmount();i++){
							synUserDisk(userArr.get(i),1,"2000-01-01 00:00:00",dateStr);
							jobMonitor.setSynCount(jobMonitor.getSynCount()+1);
							jobMonitorService.updateJobMonitor(jobMonitor);
						}
						jobMonitor.setSynTime(dateStr);
						jobMonitor.setStatus("1");
						jobMonitorService.updateJobMonitor(jobMonitor);
					}else {
						redisUtil.set(Constant.INIT_DISK_STATUS,"1",7200);
					}
				}
				if(redisUtil.hasKey(Constant.SYN_DISK_STATUS)){
					logger.info("正在执行,暂不进行统统不");
				}else {
					JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.SYN_DISK_JOB);
					if(null == jobMonitor) {
						logger.info("没有同步任务");
					}else {
						List<String> userArr = OpenUtil.getSchoolUserIds();
						redisUtil.set(Constant.SYN_DISK_STATUS,"1",7200);
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String dateStr= sdf.format(new Date());
						for (String anUserArr : userArr) {
							synUserDisk(anUserArr, 1, jobMonitor.getSynTime(), dateStr);
						}
						jobMonitor.setSynTime(dateStr);
						jobMonitor.setStatus("0");
						jobMonitorService.updateJobMonitor(jobMonitor);
						redisUtil.del(Constant.SYN_DISK_STATUS);
					}
				}
			} catch (Exception e) {
				logger.error("同步执行异常",e);
				if(redisUtil.hasKey(Constant.INIT_DISK_STATUS)){
					redisUtil.del(Constant.INIT_DISK_STATUS);
				}
				if(redisUtil.hasKey(Constant.SYN_DISK_STATUS)){
					redisUtil.del(Constant.SYN_DISK_STATUS);
				}
			}

		}


	@Scheduled(cron = "0 3/5 * * * ? ")
	public void synUserDisksToPlat(){
		try {

			if(redisUtil.hasKey(Constant.SYN_DISK_PLAT_STATUS)){
				logger.info("正在执行,暂不进行统统不");
			}else {
				JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.SYN_DISK_PLAT_JOB);
				if(null == jobMonitor) {
					logger.info("没有同步任务");
				}else {
					redisUtil.set(Constant.SYN_DISK_PLAT_STATUS,"1",7200);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String dateStr= sdf.format(new Date());
						synUserDiskPlat( 1, jobMonitor.getSynTime(), dateStr);
					jobMonitor.setSynTime(dateStr);
					jobMonitor.setStatus("0");
					jobMonitorService.updateJobMonitor(jobMonitor);
					redisUtil.del(Constant.SYN_DISK_PLAT_STATUS);
				}
			}
		} catch (Exception e) {
			logger.error("同步执行异常",e);
			if(redisUtil.hasKey(Constant.SYN_DISK_PLAT_STATUS)){
				redisUtil.del(Constant.SYN_DISK_PLAT_STATUS);
			}
		}

	}

//	@Scheduled(cron="0 15 0 * * ?")
//	@Scheduled(cron="1 */5 * * * ?")
	private void synSpecialRepo(JobMonitor jobMonitor) throws Exception{


				String url = opengateDomain + "/cms-gateway/SpecialRepoAllNoBM/"+orgId+"?accessToken="+OpenUtil.createToken();
				String aamResponse = HttpClient.doGetMethod(url);
				net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
				String resultCode = jsonObj.optString("result");
				if (Constant.SUCCESS_CODE.equals(resultCode)) {
					JSONArray list = jsonObj.optJSONArray("data");
					if(list.size() > 0) {
						List<SpecialRepo> listAdd = new ArrayList<>();
						List<SpecialRepo> listUpdate = new ArrayList<>();
						Date synTime;
						if(StringUtil.isNotEmpty(jobMonitor.getSynTime())) {
							 synTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(jobMonitor.getSynTime());
						}else {
							 synTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2000-01-01 00:00:00");
						}
//						List<String> repoIds = new ArrayList<>();
						for (int i = 0; i < list.size(); i++) {
							SpecialRepo specialRepo = new SpecialRepo();
							specialRepo.setId(list.getJSONObject(i).optString("id"));
							specialRepo.setParentId(list.getJSONObject(i).optString("parentId"));
							specialRepo.setName(list.getJSONObject(i).optString("name"));
							specialRepo.setResNum(list.getJSONObject(i).optString("resNum"));
							specialRepo.setRepoId(list.getJSONObject(i).optString("repoId"));
							specialRepo.setStatus(list.getJSONObject(i).optString("status"));
							specialRepo.setIsShow(list.getJSONObject(i).optString("isShow"));
							specialRepo.setUpdateTime(list.getJSONObject(i).optString("updateTime"));
							specialRepo.setCreateTime(list.getJSONObject(i).optString("createTime"));
							if(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(specialRepo.getUpdateTime()).after(synTime)){
								SpecialRepo specialRepo0 = specialRepoService.getSpecialRepo(specialRepo.getId());
								if(specialRepo0 == null){
									listAdd.add(specialRepo);
								}else {
									listUpdate.add(specialRepo);
								}
							}
						}
						if(listAdd.size()>0) {
							specialRepoService.batchAddSpecialRepo(listAdd);
						}
						if(listUpdate.size()>0) {
							specialRepoService.batchUploadSpecialRepo(listUpdate);
						}

					}

				}


	}





	private void synAllSpecialRepo(JobMonitor jobMonitor) throws Exception{
		String url = opengateDomain + "/cms-gateway/AllSpecialRepo/"+orgId+"?accessToken="+OpenUtil.createToken();
		String aamResponse = HttpClient.doGetMethod(url);
		net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
		String resultCode = jsonObj.optString("code");
		if (Constant.SUCCESS_CODE.equals(resultCode)) {
			JSONArray arr = jsonObj.optJSONArray("SpecialResourcesBaseList");
			JSONArray arr1 = jsonObj.optJSONArray("SpecialResourceCatalogList");
			List<SpecialResourcesBase> list = new ArrayList<>();
			List<SpecialResourceCatalog> list1 = new ArrayList<>();
			for (int i = 0; i < arr.size(); i++) {
				SpecialResourcesBase srb = new SpecialResourcesBase();
				srb.setId(arr.getJSONObject(i).optString("id"));
				srb.setTopicResourceName(arr.getJSONObject(i).optString("topicResourceName"));
				srb.setResourcesType(arr.getJSONObject(i).optInt("resourcesType"));
				srb.setIsCatalog(arr.getJSONObject(i).optInt("isCatalog"));
				srb.setUserId(arr.getJSONObject(i).optString("userId"));
				srb.setPlatfromCode(arr.getJSONObject(i).optString("platfromCode"));
				srb.setCreateTime(DateUtils.convertDateStr(arr.getJSONObject(i).optString("createTime")));
				srb.setUpdateTime(DateUtils.convertDateStr(arr.getJSONObject(i).optString("updateTime")));
				srb.setIsDelete(arr.getJSONObject(i).optString("isDelete"));
				srb.setOrgId(arr.getJSONObject(i).optString("orgId"));
				srb.setIsShow(arr.getJSONObject(i).optString("isShow"));
				srb.setVisualRange(arr.getJSONObject(i).optString("visualRange"));
				list.add(srb);
			}

			for (int i = 0; i < arr1.size(); i++) {
				SpecialResourceCatalog src = new SpecialResourceCatalog();
				src.setCatalogId(arr1.getJSONObject(i).optString("catalogId"));
				src.setCatalogName(arr1.getJSONObject(i).optString("catalogName"));
				src.setParentId(arr1.getJSONObject(i).optString("parentId"));
				src.setStatus(arr1.getJSONObject(i).optInt("status"));
				src.setTSpecialResourcesId(arr1.getJSONObject(i).optString("tSpecialResourcesId"));
				src.setCreateTime(DateUtils.convertDateStr(arr1.getJSONObject(i).optString("createTime")));
				src.setUpdateTime(DateUtils.convertDateStr(arr1.getJSONObject(i).optString("updateTime")));
				list1.add(src);
			}


			if(list.size() > 0) {
				List<SpecialResourcesBase> listAdd = new ArrayList<>();
				List<SpecialResourcesBase> listUpdate = new ArrayList<>();
				Date synTime;
				if(StringUtil.isNotEmpty(jobMonitor.getSynTime())) {
					synTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(jobMonitor.getSynTime());
				}else {
					synTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2000-01-01 00:00:00");
				}
				for (SpecialResourcesBase srb : list) {
					if(srb.getUpdateTime().after(synTime)){
						SpecialResourcesBase srb0 = specialRepoService.getSpecialRepoBase(srb.getId());
						if(srb0 == null){
							listAdd.add(srb);
						}else {
							listUpdate.add(srb);
						}
					}
				}
				if(listAdd.size()>0) {
					specialRepoService.batchAddSpecialRepoBase(listAdd);
				}
				if(listUpdate.size()>0) {
					specialRepoService.batchUploadSpecialRepoBase(listUpdate);
				}

			}

			if(list1.size() > 0) {
				List<SpecialResourceCatalog> list1Add = new ArrayList<>();
				List<SpecialResourceCatalog> list1Update = new ArrayList<>();
				Date synTime;
				if(StringUtil.isNotEmpty(jobMonitor.getSynTime())) {
					synTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(jobMonitor.getSynTime());
				}else {
					synTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2000-01-01 00:00:00");
				}

				for (SpecialResourceCatalog src : list1) {
					if(src.getUpdateTime().after(synTime)){
						SpecialResourceCatalog src0 = specialRepoService.getSpecialResCata(src.getCatalogId());
						if(src0 == null){
							list1Add.add(src);
						}else {
							list1Update.add(src);
						}
					}
				}
				if(list1Add.size()>0) {
					specialRepoService.batchAddSpecialResCata(list1Add);
				}
				if(list1Update.size()>0) {
					specialRepoService.batchUploadSpecialResCata(list1Update);
				}

			}

		}


	}












	@Scheduled(cron="3 */5 * * * ?")
	public void synSpecialResource() {

		JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.SYN_SPECIAL_REPO);
		if(null == jobMonitor) {
			logger.info("不进行初始化");
		}else if("0".equals(jobMonitor.getStatus())) {
			logger.info("开始同步专题资源库");
			String synUserDisksStatus = null;
			if(redisUtil.hasKey(Constant.SYN_SPECIAL_REPO_STATUS)){
				synUserDisksStatus = (String) redisUtil.get(Constant.SYN_SPECIAL_REPO_STATUS);
			}
			logger.info("同步状态码："+synUserDisksStatus);
			if(StringUtils.isNotEmpty(synUserDisksStatus) && "1".equals(synUserDisksStatus)){
				logger.info("已有"+Constant.SYN_SPECIAL_REPO_STATUS+"进程执行,不进行同步");
			}else {
				try {
					redisUtil.set(Constant.SYN_SPECIAL_REPO_STATUS, "1", 7200);

					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String dateStr = sdf.format(new Date());
					synSpecialRepo(jobMonitor);
					logger.info("分表同步数据");
					synAllSpecialRepo(jobMonitor);
					List<SpecialRepo> list = specialRepoService.getSpecialRepoList("ZT");
					for (SpecialRepo specialRepo : list) {
						synRepo(specialRepo.getId(), 1, jobMonitor.getSynTime(), dateStr);
					}
					jobMonitor.setSynTime(dateStr);
					jobMonitorService.updateJobMonitor(jobMonitor);
					redisUtil.del(Constant.SYN_SPECIAL_REPO_STATUS);
				}catch (Exception e){
					logger.error("同步专题资源库列表失败",e);
					redisUtil.del(Constant.SYN_SPECIAL_REPO_STATUS);
				}
			}
		}
	}

	@Scheduled(cron="1 * * * * ?")
	public void initSpecialRepo() {
		if(!isCloud&&!redisUtil.hasKey(Constant.SYN_SPECIAL_REPO)) {
			JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.SYN_SPECIAL_REPO);
			if(null == jobMonitor) {
				try {
					JobMonitor monitor0 = new JobMonitor();
					monitor0.setJobId(Constant.SYN_SPECIAL_REPO);
					monitor0.setStatus("0");
					monitor0.setSynCount(0);
					monitor0.setUserIds("");
					monitor0.setSynTime("2000-01-01 00:00:00");
					jobMonitorService.addJobMonitor(monitor0);
					redisUtil.set(Constant.SYN_SPECIAL_REPO,"1",7200);
				} catch (Exception e) {
					logger.error("获取教师列表异常",e);
				}
			}
		}
	}

	@Scheduled(cron="1 * * * * ?")
	public void initProdOwner() {
		if(!isCloud&&!redisUtil.hasKey(Constant.INIT_PROD_OWNER)) {
			JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.INIT_PROD_OWNER);
			if(null == jobMonitor) {
				try {
					JobMonitor monitor0 = new JobMonitor();
					monitor0.setJobId(Constant.INIT_PROD_OWNER);
					monitor0.setStatus("0");
					monitor0.setSynCount(0);
					monitor0.setUserIds("");
					jobMonitorService.addJobMonitor(monitor0);
					redisUtil.set(Constant.INIT_PROD_OWNER,"1",7200);
				} catch (Exception e) {
					logger.error("获取教师列表异常",e);
				}
			}
		}
	}

	@Scheduled(cron="0 8,23,38,53 * * * ?")
	public void synProdOwners() {
		try {
			JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.INIT_PROD_OWNER);
			if (null == jobMonitor) {
				logger.info("不进行同步");
			} else if ("0".equals(jobMonitor.getStatus())) {
				String synProdStatus = null;
				if (redisUtil.hasKey(Constant.INIT_PROD_OWNER + "_status")) {
					synProdStatus = (String) redisUtil.get(Constant.INIT_PROD_OWNER + "_status");
				}
				if (StringUtils.isNotEmpty(synProdStatus) && "1".equals(synProdStatus)) {
					logger.info("已有进程执行,不进行同步");
				} else {
					redisUtil.set("syn_prod_owner_status", "1",7200);
					redisUtil.del(Constant.INIT_PROD_OWNER);
				//暂时全量执行
					synProdOwner(1);
					redisUtil.del("syn_prod_owner_status");

//					jobMonitor.setStatus("3");
//					jobMonitorService.updateJobMonitor(jobMonitor);

				}
			}
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			logger.error("同步校本资源异常");
			if(redisUtil.hasKey(Constant.INIT_PROD_OWNER)){
				redisUtil.del(Constant.INIT_PROD_OWNER);
			}
			if(redisUtil.hasKey("syn_prod_owner_status")){
				redisUtil.del("syn_prod_owner_status");
			}
			//异常后
		}

	}

	void synUserDisk(String id,int curPage,String modifyTimeBegin,String modifyTimeEnd)throws Exception{
		String url = opengateDomain + "/cms-gateway/listResources?accessToken="+OpenUtil.createToken();
		JSONObject param = new JSONObject();
		JSONObject page = new JSONObject();
		JSONObject query = new JSONObject();
		page.put("curPage",curPage);
		page.put("numPerPage",100);
		query.put("userId",id);
		query.put("ownerType","0");
		query.put("modifyTimeBegin",modifyTimeBegin);
		query.put("modifyTimeEnd",modifyTimeEnd);
		query.put("resForm","1");
		param.put("page",page);
		param.put("query",query);
		String aamResponse = HttpClient.doJSONPostMethod(url, param.toJSONString());
		net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
		String resultCode = jsonObj.optString("result");
		if (Constant.SUCCESS_CODE.equals(resultCode)) {
			net.sf.json.JSONObject  jsonData = jsonObj.optJSONObject("data");
			int totalCount=	jsonData.optInt("count");
			JSONArray list = jsonData.optJSONArray("list");
			List<DiskOwner> listAdd = new ArrayList<>();
			List<DiskOwner> listUpdate= new ArrayList<>();
			if(list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					int existsNum = diskService.selectDiskExists(list.getJSONObject(i).optString("dirId"));
					DiskOwner diskOwner = exchangeData(list.getJSONObject(i));
					if(existsNum<1) {
						listAdd.add(diskOwner);
						AttachFile attachFile = new AttachFile();
						 if(diskOwner.getFid()!=null){
							 AttachFile attachFile0 = attachFileService.getAttachFile(Long.valueOf(diskOwner.getFid()));
							 if(attachFile0 == null ) {
								 attachFile.setFid(Long.valueOf(diskOwner.getFid()));
								 attachFile.setFileMd5(diskOwner.getFileMd5());
								 attachFile.setFileSize(diskOwner.getFileSize());
								 attachFile.setFileExt(diskOwner.getFileExt());
								 attachFile.setFileLength(diskOwner.getFileLength());
								 attachFile.setIsPlatform("1");
								 attachFile.setIsLocal("0");
								 attachFile.setFileMd5(diskOwner.getFileMd5());
								 attachFile.setFileNameLocal(diskOwner.getDirName());
								 attachFile.setOrgId(orgId);
								 attachFile.setUserId(id);
								 attachFile.setAttachFrom("0");
								 attachFile.setCreateTime(attachFile.getCreateTime());
								 if (StringUtil.isNotEmpty(diskOwner.getDownloadUrlHjy()) || 1 == diskOwner.getIsFileCenter()) {
									 attachFile.setIsFileCenter(1);
								 }
								 attachFileService.addAttachFile(attachFile);
							 }
                        }
					}else {
						listUpdate.add(diskOwner);
					}
				}
				if(listAdd.size()>0) {
					diskService.saveDiskOwnerBatch(listAdd);
				}
				if(listUpdate.size()>0) {
					diskService.batchUpdateDiskOwner(listUpdate);
				}
				if(curPage*100<totalCount){
					synUserDisk(id,curPage+1,modifyTimeBegin,modifyTimeEnd);
				}
			}
		}
	}

	void synUserDiskPlat(int curPage,String modifyTimeBegin,String modifyTimeEnd)throws Exception{
		PageHelper.startPage(curPage, 20);
		List<DiskOwner> diskOwnerList = null;
		DiskOwner diskOwner = new DiskOwner();
		diskOwner.setModifyTimeBegin(modifyTimeBegin);
		diskOwner.setModifyTimeEnd(modifyTimeEnd);
		diskOwnerList = diskService.queryDiskOwner(diskOwner);
		PageInfo<DiskOwner> pageInfo = new PageInfo<>(diskOwnerList);
		JSONObject param = new JSONObject();
		if(pageInfo.getList().size()==0){
			logger.info("无更新");
		}else {
			for (DiskOwner diskOwner1 : pageInfo.getList()) {
				if ("1".equals(diskOwner1.getIsFolder())&&StringUtils.isNotBlank(diskOwner1.getFid())) {
					AttachFile attachFile0 = attachFileService.getAttachFile(Long.valueOf(diskOwner1.getFid()));
					if(attachFile0 != null &&!"0".equals(attachFile0.getAttachFrom())) {
						AttachFile attachFile = new AttachFile();
						attachFile.setFid(Long.valueOf(diskOwner1.getFid()));
						attachFile.setAttachFrom("0");
						attachFileService.modAttachFile(attachFile);
					}
				}
			}
			param.put("diskList", pageInfo.getList());
			String url = opengateDomain + "/cms-gateway/batchSynDiskResource?accessToken=" + OpenUtil.createToken();
			String aamResponse = HttpClient.doJSONPostMethod(url, param.toJSONString());
			net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
			String resultCode = jsonObj.optString("result");
			if (Constant.SUCCESS_CODE.equals(resultCode)) {
				if (curPage * 20 < pageInfo.getTotal()) {
					synUserDiskPlat(curPage + 1, modifyTimeBegin, modifyTimeEnd);
				}
			}
		}
	}

	void synProdOwner(int curPage) throws Exception{

			String url = opengateDomain + "/cms-gateway/getResByChapterId?accessToken="+OpenUtil.createToken();
			JSONObject param = new JSONObject();
			param.put("curPage",curPage);
			param.put("pageSize",1000);
			param.put("orgId",orgId);
			param.put("isDelete","all");
			String aamResponse = HttpClient.doJSONPostMethod(url, param.toJSONString());
			net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
			String resultCode = jsonObj.optString("result");
			if (Constant.SUCCESS_CODE.equals(resultCode)) {
				int totalCount= Integer.parseInt(jsonObj.optString("count"));
				JSONArray list = jsonObj.optJSONArray("data");
				List<ProdOwner> listAdd = new ArrayList<>();
				List<ProdOwner> listUpdate = new ArrayList<>();

				if(list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						int existsNum = schoolResourceService.selectProdOwnerExists(list.getJSONObject(i).optString("productCode"));
						ProdOwner prodOwner = new ProdOwner();
						String resId = list.getJSONObject(i).optString("resId");
						String productCode = list.getJSONObject(i).optString("productCode");
						String resName = list.getJSONObject(i).optString("resName");
						String ext = list.getJSONObject(i).optString("ext");
						Long fileLength = list.getJSONObject(i).optLong("fileLength");
						String fileSize = list.getJSONObject(i).optString("fileSize");
						String previewUrl = list.getJSONObject(i).optString("previewUrl");
						String downUrl = list.getJSONObject(i).optString("downUrl");
						String fid = list.getJSONObject(i).optString("fid");
						String creatorId = list.getJSONObject(i).optString("creatorId");
						String viewCount = list.getJSONObject(i).optString("viewCount");
						String downCount = list.getJSONObject(i).optString("downCount");
						String collectCount = list.getJSONObject(i).optString("collectCount");
						String score = list.getJSONObject(i).optString("score");
						String chapterId = list.getJSONObject(i).optString("chapterId");
						String creatorName = list.getJSONObject(i).optString("creatorName");
						String createTime = list.getJSONObject(i).optString("createTime");
						String formatId =  list.getJSONObject(i).optString("formatId");
						String isDelete =  list.getJSONObject(i).optString("isDelete");
						String classificationId = list.getJSONObject(i).optString("classificationId");
						String isFileCenter = list.getJSONObject(i).optString("isFileCenter");
						String auditStatus = list.getJSONObject(i).optString("auditStatus");
						prodOwner.setResId(resId);
						prodOwner.setProductCode(productCode);
						prodOwner.setProductName(resName);
						prodOwner.setFileExt(ext);
						prodOwner.setFileSize(fileSize);
						prodOwner.setFileLength(fileLength);
						prodOwner.setPreviewUrl(previewUrl);
						prodOwner.setDownloadUrl(downUrl);
						prodOwner.setCreatorId(creatorId);
						prodOwner.setFId(fid);
						prodOwner.setViewCount(Long.valueOf(viewCount));
						prodOwner.setDownCount(Long.valueOf(downCount));
						prodOwner.setCollectedCount(Long.valueOf(collectCount));
						prodOwner.setScore(Float.valueOf(score));
						prodOwner.setChapterId(chapterId);
						prodOwner.setCreatorName(creatorName);
						prodOwner.setCreateTime(createTime);
						prodOwner.setFormatId(formatId);
						prodOwner.setClassificationId(classificationId);
						prodOwner.setIsDelete(isDelete);
						prodOwner.setIsFileCenter(isFileCenter);
						prodOwner.setAuditStatus(auditStatus);
						if(existsNum<1) {
							AttachFile attachFile = new AttachFile();
							if(StringUtils.isNotBlank(prodOwner.getFId())){
								attachFile.setFid(Long.valueOf(prodOwner.getFId()));
								attachFile.setFileMd5(prodOwner.getFileMd5());
								attachFile.setFileSize(prodOwner.getFileSize());
								attachFile.setFileExt(prodOwner.getFileExt());
								attachFile.setFileLength(prodOwner.getFileLength());
								attachFile.setIsPlatform("1");
								attachFile.setIsLocal("0");
								attachFile.setFileMd5(prodOwner.getFileMd5());
								attachFile.setFileNameLocal(prodOwner.getProductName());
								attachFile.setOrgId(orgId);
								attachFile.setUserId(creatorId);
								attachFile.setAttachFrom("0");
								attachFile.setCreateTime(attachFile.getCreateTime());
								if("1".equals(prodOwner.getIsFileCenter())){
									attachFile.setIsFileCenter(1);
									attachFile.setIsCloud("1");
								}
								AttachFile attachFile1 = attachFileService.getAttachFile(Long.valueOf(prodOwner.getFId()));
								if(attachFile1 == null) {
									attachFileService.addAttachFile(attachFile);
								}
								listAdd.add(prodOwner);
							}

						}else {
							listUpdate.add(prodOwner);
						}
					}
					if(listAdd.size()>0){
						schoolResourceService.saveSchoolResBatch(listAdd);
					}
					if(listUpdate.size()>0){
						schoolResourceService.batchUpdateProdOwner(listUpdate);
					}
					if(curPage*1000<totalCount){
						synProdOwner(curPage+1);
					}
				}
			}


	}

	void synRepo(String repoId,int curPage,String modifyTimeBegin,String modifyTimeEnd) throws Exception{
			logger.info("开始同步"+repoId+"专题资源库");
			String url = opengateDomain + "/cms-gateway/getRepoResourceListByCatalog?accessToken=" + OpenUtil.createToken();
			JSONObject param = new JSONObject();
			param.put("curPage", curPage);
			param.put("pageSize", 1000);
			param.put("isCatalog", "0");
			param.put("repoId", repoId);
			param.put("all","all");
			param.put("type","1");
			param.put("startUpdateTime", modifyTimeBegin);
			param.put("endUpdateTime", modifyTimeEnd);
			logger.info("同步资源库参数"+param);
			String aamResponse = HttpClient.doJSONPostMethod(url, param.toJSONString());
			net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
			logger.info("同步资源库返回"+jsonObj);
			String resultCode = jsonObj.optString("result");
			if (Constant.SUCCESS_CODE.equals(resultCode)) {
				int totalCount = Integer.parseInt(jsonObj.optString("count"));
				JSONArray list = jsonObj.optJSONArray("data");
				List<ProdOwner> listAdd = new ArrayList<>();
				List<ProdOwner> listUpdate = new ArrayList<>();
				if (list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						ProdOwner prodOwner = new ProdOwner();
						String resId = list.getJSONObject(i).optString("resId");
						String productCode = list.getJSONObject(i).optString("id");
						String resName = list.getJSONObject(i).optString("resName");
						String ext = list.getJSONObject(i).optString("ext");
						String fileLength = list.getJSONObject(i).optString("fileLength");
						String fileSize = list.getJSONObject(i).optString("fileSize");
						String previewUrl = list.getJSONObject(i).optString("previewUrl");
						String downUrl = list.getJSONObject(i).optString("downUrl");
						String fid = list.getJSONObject(i).optString("fid");
						String chapterId = list.getJSONObject(i).optString("catalogId");
						String fileMd5 = list.getJSONObject(i).optString("fileMd5");
						String updateTime = list.getJSONObject(i).optString("updateTime");
						String createTime = list.getJSONObject(i).optString("createTime");
						String isDelete = list.getJSONObject(i).optString("status");
						String auditStatus = list.getJSONObject(i).optString("auditStatus");
//						String creatorId = list.getJSONObject(i).optString("creatorId");
//						String viewCount = list.getJSONObject(i).optString("viewCount");
//						String downCount = list.getJSONObject(i).optString("downCount");
//						String collectCount = list.getJSONObject(i).optString("collectCount");
//						String score = list.getJSONObject(i).optString("score");
						prodOwner.setResId(resId);
						prodOwner.setProductCode(productCode);
						prodOwner.setProductName(resName);
						prodOwner.setFileExt(ext);
						prodOwner.setFileSize(fileSize);
						prodOwner.setFileMd5(fileMd5);
						prodOwner.setIsDelete(isDelete);
						prodOwner.setAuditStatus(auditStatus);
						if(StringUtil.isNotEmpty(fileLength)) {
							prodOwner.setFileLength(Long.valueOf(fileLength));
						}
						prodOwner.setModifyTime(updateTime);
						prodOwner.setCreateTime(createTime);
						prodOwner.setPreviewUrl(previewUrl);
						prodOwner.setDownloadUrl(downUrl);
//						prodOwner.setCreatorId(creatorId);
						prodOwner.setFId(fid);
//						prodOwner.setViewCount(Long.valueOf(viewCount));
//						prodOwner.setDownCount(Long.valueOf(downCount));
//						prodOwner.setCollectedCount(Long.valueOf(collectCount));
//						prodOwner.setScore(Float.valueOf(score));
						prodOwner.setChapterId(chapterId);
						prodOwner.setRepoId(repoId);
						int existsNum = schoolResourceService.selectProdOwnerExists(productCode);
						if(existsNum<1) {
							AttachFile attachFile = new AttachFile();
							if(prodOwner.getFId()!=null){
								attachFile.setFid(Long.valueOf(prodOwner.getFId()));
								attachFile.setFileMd5(prodOwner.getFileMd5());
								attachFile.setFileSize(prodOwner.getFileSize());
								attachFile.setFileExt(prodOwner.getFileExt());
								attachFile.setFileLength(prodOwner.getFileLength());
								attachFile.setIsPlatform("1");
								attachFile.setIsLocal("0");
								attachFile.setFileMd5(prodOwner.getFileMd5());
								attachFile.setFileNameLocal(prodOwner.getProductName());
								attachFile.setOrgId(orgId);
								attachFile.setUserId("admin");
								attachFile.setAttachFrom("0");
								attachFile.setCreateTime(createTime);
								if(prodOwner.getDownloadUrl().contains("myqcloud")){
									attachFile.setIsFileCenter(1);
								}
								AttachFile attachFile1 = attachFileService.getAttachFile(Long.valueOf(prodOwner.getFId()));
								if(attachFile1 == null) {
									attachFileService.addAttachFile(attachFile);
								}
							}
							listAdd.add(prodOwner);
						}else {
							listUpdate.add(prodOwner);
						}
					}
					if(listAdd.size()>0) {
						schoolResourceService.saveSchoolResBatch(listAdd);
					}
					if(listUpdate.size()>0) {
						schoolResourceService.batchUpdateProdOwner(listUpdate);
					}
					if (curPage * 1000 < totalCount) {
						synRepo(repoId,curPage + 1,modifyTimeBegin,modifyTimeEnd);
					}
				}
			}

	}
	 DiskOwner exchangeData(net.sf.json.JSONObject jsonObj ){
		DiskOwner diskOwner = new DiskOwner();
		String dirId = jsonObj.optString("dirId");
		String dirName = jsonObj.optString("dirName");
		String resId = jsonObj.optString("resId");
		String parentId = jsonObj.optString("parentId");
		String userId = jsonObj.optString("userId");
		String orgId = jsonObj.optString("orgId");
		String groupId = jsonObj.optString("groupId");
		String isFolder = jsonObj.optString("isFolder");
		String canRemoved = jsonObj.optString("canRemoved");
		String fileLength = jsonObj.optString("fileLength");
		String fileExt = jsonObj.optString("fileExt");
		String fileSize = jsonObj.optString("fileSize");
         String fileMd5 = jsonObj.optString("fileMd5");
         String isDelete = jsonObj.optString("isDelete");
		 String formatId = jsonObj.optString("formatId");
		 String downloadUrlHjy = jsonObj.optString("downloadUrlHjy");
		String previewUrlHjy = jsonObj.optString("previewUrlHjy");
		String fid = jsonObj.optString("fid");
		String title = jsonObj.optString("title");
		diskOwner.setDirId(dirId);
		diskOwner.setDirName(dirName);
		diskOwner.setResId(resId);
		diskOwner.setParentId(parentId);
		diskOwner.setUserId(userId);
		diskOwner.setOrgId(orgId);
		diskOwner.setGroupId(groupId);
		diskOwner.setIsFolder(isFolder);
		diskOwner.setCanRemoved(canRemoved);
		diskOwner.setTitle(title);
		diskOwner.setIsDelete(isDelete);
		diskOwner.setFormatId(formatId);
		if(StringUtil.isNotEmpty(fileLength)){
			diskOwner.setFileLength(Long.valueOf(fileLength));
		}
		diskOwner.setIsFileCenter(jsonObj.optInt("isFileCenter"));
		diskOwner.setFileExt(fileExt);
		diskOwner.setFileSize(fileSize);
		diskOwner.setFileMd5(fileMd5);
		diskOwner.setCreateTime(jsonObj.optString("createTime"));
		diskOwner.setDownloadUrlHjy(downloadUrlHjy);
		diskOwner.setPreviewUrlHjy(previewUrlHjy);
		if(StringUtil.isNotEmpty(fid)){
			diskOwner.setFid(fid);
		}
		return diskOwner;
	}



	@Scheduled(cron="0 0 23 * * ?")//每天晚上11点执行
	public void synSchoolResPrivData() {
		logger.info("synSchoolResPrivData Start:"+System.currentTimeMillis());
		try {
			JobMonitor jobMonitor = jobMonitorService.getJobMonitor(Constant.INIT_SCHOOL_RES_PRIV);
			if (null == jobMonitor) {
				logger.info("不进行同步");
			} else if ("0".equals(jobMonitor.getStatus())) {
				String synSchoolResStauts = null;
				if (redisUtil.hasKey(Constant.SYN_SCHOOL_RES_PRIV + "_status")) {
					synSchoolResStauts = (String) redisUtil.get(Constant.SYN_SCHOOL_RES_PRIV + "_status");
				}
				if (StringUtils.isNotEmpty(synSchoolResStauts) && "1".equals(synSchoolResStauts)) {
					logger.info("已有进程执行,不进行同步");
				} else {
					redisUtil.set(Constant.SYN_SCHOOL_RES_PRIV + "_status", "1",7200);
					redisUtil.del(Constant.INIT_SCHOOL_RES_PRIV);
					//暂时全量执行
					synSchoolResPriv(1);
					redisUtil.del(Constant.SYN_SCHOOL_RES_PRIV + "_status");
				}
			}
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			logger.error("同步校本资源异常");
			if(redisUtil.hasKey(Constant.INIT_SCHOOL_RES_PRIV)){
				redisUtil.del(Constant.INIT_SCHOOL_RES_PRIV);
			}
			if(redisUtil.hasKey(Constant.SYN_SCHOOL_RES_PRIV + "_status")){
				redisUtil.del(Constant.SYN_SCHOOL_RES_PRIV + "_status");
			}
			//异常后
		}
		logger.info("synSchoolResPrivData End:"+System.currentTimeMillis());

	}

	private void synSchoolResPriv(int curPage) throws Exception {

		//		t_visual_range_priv
		String url = opengateDomain + "/cms-gateway/getSchoolResPrivs?accessToken="+OpenUtil.createToken();
		JSONObject param = new JSONObject();
		param.put("curPage",curPage);
		param.put("pageSize",1000);
		param.put("orgId",orgId);
		String aamResponse = HttpClient.doJSONPostMethod(url, param.toJSONString());
		net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
		String resultCode = jsonObj.optString("result");
		if (Constant.SUCCESS_CODE.equals(resultCode)) {
			int totalCount= Integer.parseInt(jsonObj.optString("count"));
			JSONArray list = jsonObj.optJSONArray("data");
			List<VisualRangePrivDto> listAdd = new ArrayList<>();
			List<VisualRangePrivDto> listUpdate = new ArrayList<>();

			if(list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					net.sf.json.JSONObject jsonObject = list.getJSONObject(i);
					int existsNum = schoolResourceService.getSchoolResPrivExist(jsonObject.optString("privId"));
					VisualRangePrivDto prodOwner = JSON.parseObject(jsonObject.toString(),VisualRangePrivDto.class);
					if(existsNum<1) {//不存在
							listAdd.add(prodOwner);
					}else {
						listUpdate.add(prodOwner);
					}
				}
				if(listAdd.size()>0){
					schoolResourceService.saveSchoolResPrivBatch(listAdd);
				}
				if(listUpdate.size()>0){
					schoolResourceService.batchUpSchoolResPriv(listUpdate);
				}
				if(curPage*1000<totalCount){
					synProdOwner(curPage+1);
				}
			}
		}

	}

	/**
	 * 同步上报资源到平台
	 */
	@Scheduled(cron = "0 3/5 * * * ? ")
	public void synReportResourceToPlat(){
		try {
			if(!isCloud) {
				logger.info("开始同步校本资源到平台");
				synReportResource(1);
			}
		} catch (Exception e) {
			logger.error("同步执行异常",e);
			if(redisUtil.hasKey(Constant.SYN_DISK_PLAT_STATUS)){
				redisUtil.del(Constant.SYN_DISK_PLAT_STATUS);
			}
		}

	}


	void synReportResource(int curPage)throws Exception{

		Pagination pagination = new Pagination();
		pagination.setCurPage(curPage);
		pagination.setNumPerPage(20);
		//同步审核通过,校园主机上传未同步的资源
		ProdOwner prodOwner = new ProdOwner();
		//prodOwner.setAuditStatus("1");
		prodOwner.setIsXyzjUpload("1");
		prodOwner.setIsSync("0");
		PageInfo<ProdOwner> pageInfo = schoolResourceService.queryForSchResPagination(pagination,prodOwner);
		List<ProdOwner> list = pageInfo.getList();
		List<String> productCodeList = new ArrayList<>();
		JSONObject param = new JSONObject();
		if(list.size()==0){
			logger.info("无更新");
		}else {
			for(ProdOwner pd : list){
				productCodeList.add(pd.getProductCode());
			}
			param.put("prodOwer", list);
			logger.info("同步资源库参数"+param);
			String url = opengateDomain + "/cms-gateway/synReportResource?accessToken=" + OpenUtil.createToken();
			String aamResponse = HttpClient.doJSONPostMethod(url, param.toJSONString());
			net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(aamResponse);
			boolean success = jsonObj.optBoolean("success");
			if (success) {
				schoolResourceService.batchUpdateSync(productCodeList);
				if (curPage * 20 < pageInfo.getTotal()) {
					synReportResource(curPage + 1);
				}
			}
		}
	}
}
